<template>
  <div class="w-screen min-h-screen mx-auto p-4">
    <div class="flex flex-col md:flex-row gap-4 max-w-full">
      <!-- 表单区域 -->
      <div class="w-full md:w-1/2 min-h-screen">
        <el-card class="h-full">
          <template #header>
            <div class="flex justify-between items-center">
              <h2 class="text-xl font-semibold">
                简历信息填写<span class="text-xs text-gray-500 ml-1">(以最后一次提交为准)</span>
              </h2>
            </div>
          </template>
          <div class="p-2 space-y-4">
            <el-form
              ref="formRef"
              :model="resume"
              :rules="rules"
              label-width="auto"
              style="max-width: 600px"
              label-position="top"
            >
              <el-row :gutter="16">
                <el-col :xs="24" :sm="12">
                  <el-form-item label="姓名" prop="name">
                    <el-input
                      :maxlength="15"
                      id="name"
                      v-model="resume.name"
                      type="text"
                      placeholder="请输入姓名"
                      size="large"
                      clearable
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12">
                  <el-form-item label="专业" prop="major">
                    <el-input
                      :maxlength="10"
                      id="major"
                      v-model="resume.major"
                      type="text"
                      placeholder="请输入专业"
                      :autosize="{ minRows: 2, maxRows: 4 }"
                      size="large"
                      clearable
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="16">
                <el-col :xs="24" :sm="12">
                  <el-form-item label="班级" prop="class">
                    <el-input
                      :maxlength="6"
                      id="class"
                      v-model="resume.class"
                      type="text"
                      placeholder="请输入班级"
                      size="large"
                      clearable
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12">
                  <el-form-item label="发展方向" prop="direction">
                    <el-select
                      id="direction"
                      v-model="resume.direction"
                      size="large"
                      clearable
                      placeholder="请选择发展方向"
                    >
                      <el-option value="前端开发">前端开发</el-option>
                      <el-option value="后端开发">后端开发</el-option>
                      <el-option value="人工智能">人工智能(CV/NLP)</el-option>
                      <el-option value="数学建模">数学建模</el-option>
                      <el-option value="创赛运营">创赛运营</el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="16">
                <el-col :xs="24" :sm="12">
                  <el-form-item label="电话号码" prop="phone">
                    <el-input
                      :maxlength="11"
                      id="phone"
                      v-model="resume.phone"
                      type="text"
                      placeholder="请输入电话号码"
                      size="large"
                      clearable
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12">
                  <el-form-item label="邮箱" prop="email">
                    <el-input
                      :maxlength="30"
                      id="email"
                      v-model="resume.email"
                      type="text"
                      placeholder="请输入邮箱"
                      size="large"
                      clearable
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="兴趣爱好" prop="hobbies">
                <el-input
                  id="hobbies"
                  v-model="resume.hobbies"
                  type="textarea"
                  :maxlength="120"
                  show-word-limit
                  placeholder="请输入你的兴趣爱好"
                  :rows="2"
                  clearable
                />
              </el-form-item>

              <el-form-item label="个人规划" prop="personalPlan">
                <el-input
                  id="personalPlan"
                  :maxlength="200"
                  show-word-limit
                  v-model="resume.personalPlan"
                  placeholder="请描述你的个人发展规划"
                  :rows="4"
                  type="textarea"
                  clearable
                />
              </el-form-item>

              <el-form-item label="对团队的期待" prop="joinReason" class="w-full">
                <el-input
                  id="joinReason"
                  :maxlength="200"
                  show-word-limit
                  v-model="resume.joinReason"
                  placeholder="请说明你对团队的期待"
                  :rows="4"
                  type="textarea"
                  clearable
                />
              </el-form-item>

              <el-form-item label="对本方向的理解，学习进度(如有)">
                <el-input
                  id="skills"
                  :maxlength="120"
                  show-word-limit
                  v-model="resume.skills"
                  placeholder="请输入你对本方向的理解，学习进度(如有)"
                  :rows="3"
                  type="textarea"
                  clearable
                />
              </el-form-item>
            </el-form>
          </div>
          <template #footer>
            <el-button
              type="primary"
              :loading="isLoading"
              @click="downloadResumePDF(formRef)"
              size="large"
              class="w-full"
              >提交并下载PDF简历</el-button
            >
          </template>
        </el-card>
      </div>

      <!-- 预览区域 -->
      <div class="w-full md:w-1/2">
        <div class="bg-gray-50 min-h-[600px] md:min-h-screen p-4 md:p-10">
          <div
            class="max-w-[800px] my-0 mx-auto p-4 md:p-[3rem] bg-white rounded-lg relative min-h-[1123px]"
            id="PDF-content"
          >
            <!-- 右上角标识 -->
            <div
              class="flex justify-end md:text-xs text-[0.65rem] text-gray-600 opacity-50 absolute top-8 md:right-[3rem] right-[1rem]"
            >
              {{ dayjs().format("YYYY-MM-DD") }} @ 图灵智能创新团队
            </div>

            <!-- 个人信息头部 -->
            <div class="border-gray-800 relative flex items-end mb-16 mt-4 justify-between">
              <div class="flex-col flex gap-5 flex-1 flex-shrink-0">
                <div class="text-4xl md:text-7xl text-black tracking-wider">
                  {{ resume.name || "姓名" }}
                </div>
                <div class="text-2xl md:text-4xl text-gray-600 tracking-wider">
                  {{ resume.direction || "发展方向" }}
                </div>
              </div>

              <div
                class="md:text-xl text-[0.65rem] font-light text-gray-500 tracking-wide flex-col flex absolute right-0 bottom-0"
              >
                <div class="text-right">{{ resume.major || "专业" }} | {{ resume.class || "班级" }}</div>
                <div class="text-right">{{ resume.phone || "联系方式" }} | {{ resume.email || "邮箱地址" }}</div>
              </div>
            </div>

            <!-- 内容区域 -->
            <div class="flex flex-col gap-14">
              <!-- 兴趣爱好 -->
              <div class="group">
                <div
                  class="text-2xl text-gray-900 uppercase tracking-wider pb-3 border-b-2 border-gray-200 group-hover:border-gray-400 duration-200 flex-col items-center"
                >
                  <div class="flex items-center">
                    <div class="flex items-center">兴趣爱好</div>
                  </div>
                </div>
                <div class="mt-2">
                  <p class="text-gray-700 text-base leading-relaxed tracking-wide">
                    {{ resume.hobbies || "请填写兴趣爱好" }}
                  </p>
                </div>
              </div>

              <!-- 个人规划 -->
              <div class="group">
                <div
                  class="text-2xl text-gray-900 uppercase tracking-wider pb-3 border-b-2 border-gray-200 group-hover:border-gray-400 duration-200 flex-col items-center"
                >
                  <div class="flex items-center">
                    <div class="flex items-center">个人规划</div>
                  </div>
                </div>
                <div class="mt-2">
                  <p class="text-gray-700 text-base leading-relaxed tracking-wide">
                    {{ resume.personalPlan || "请填写个人规划" }}
                  </p>
                </div>
              </div>

              <!-- 对团队的期待 -->
              <div class="group">
                <div
                  class="text-2xl text-gray-900 uppercase tracking-wider pb-3 border-b-2 border-gray-200 group-hover:border-gray-400 duration-200 flex-col items-center"
                >
                  <div class="flex items-center">
                    <div class="flex items-center">对团队的期待</div>
                  </div>
                </div>
                <div class="mt-2">
                  <p class="text-gray-700 text-base leading-relaxed tracking-wide">
                    {{ resume.joinReason || "请填写对团队的期待" }}
                  </p>
                </div>
              </div>

              <!-- 对本方向的理解，学习进度(如有) -->
              <div class="group">
                <div
                  class="text-2xl text-gray-900 uppercase tracking-wider pb-3 border-b-2 border-gray-200 group-hover:border-gray-400 duration-200 flex-col items-center"
                >
                  <div class="flex items-center">
                    <div class="flex items-center">对本方向的理解，学习进度(如有)</div>
                  </div>
                </div>
                <div class="mt-2">
                  <p class="text-gray-700 text-base leading-normal tracking-wide">
                    {{ resume.skills || "请填写对本方向的理解，学习进度(如有)" }}
                  </p>
                </div>
              </div>
            </div>

            <!-- 底部标识 -->
            <div
              class="flex justify-between items-center text-gray-500 text-sm absolute bottom-8 w-full px-[3rem] right-0"
            >
              <div class="w-6 h-[1px] bg-gray-500"></div>
              <div>TURING</div>
              <div class="w-6 h-[1px] bg-gray-500"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import html2canvas from "html2canvas";
import { jsPDF } from "jspdf";
import type { FormInstance } from "element-plus";
import type { FormRules } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { useResumeStore } from "../stores";
import { useResumeQuery } from "../composables/useResumeQuery";
import type { ResumeData as RuleForm } from "../types";
import dayjs from "dayjs";

const formRef = ref<FormInstance>();

const resumeStore = useResumeStore();
const { postResumeMutation, isLoading } = useResumeQuery();

const resume = ref<RuleForm>({
  name: "",
  major: "",
  class: "",
  direction: "",
  hobbies: "",
  personalPlan: "",
  joinReason: "",
  skills: "",
  phone: "",
  email: ""
});

const rules = ref<FormRules<RuleForm>>({
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  major: [{ required: true, message: "请输入专业", trigger: "blur" }],
  class: [{ required: true, message: "请输入班级", trigger: "blur" }],
  hobbies: [{ required: true, message: "请输入兴趣爱好", trigger: "blur" }],
  direction: [{ required: true, message: "请选择发展方向", trigger: "blur" }],
  personalPlan: [{ required: true, message: "请输入个人规划", trigger: "blur" }],
  joinReason: [{ required: true, message: "请输入对团队的期待", trigger: "blur" }],
  phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  email: [{ required: true, message: "请输入邮箱", trigger: "blur" }]
});

// 显示PC端推荐提示
const alertMobile = async () => {
  return ElMessageBox.alert("检测到您正在使用手机填写，推荐用电脑填写。", "提示", {
    confirmButtonText: "我知道了",
    type: "info",
    showClose: false,
    closeOnClickModal: false,
    closeOnPressEscape: false
  });
};

const isMobile = () => {
  const ua = navigator.userAgent;
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Mobile/i.test(ua);
};

onMounted(async () => {
  if (isMobile()) {
    await alertMobile();
  }
  const resumeData = resumeStore.getResumeData();
  if (resumeData) {
    resume.value = JSON.parse(resumeData);
  }
});

const generatePDF = async () => {
  try {
    ElMessage.info("正在生成PDF，请稍候...");
    const tempContainer = document.createElement("div");
    tempContainer.style.position = "absolute";
    tempContainer.style.left = "-9999px";
    tempContainer.style.top = "-9999px";
    tempContainer.style.width = "800px";
    tempContainer.innerHTML = `
        <div class="max-w-[800px] my-0 mx-auto p-[3rem] bg-white rounded-lg relative min-h-[1123px]" id="PDF-content">
          <!-- 右上角标识 -->
          <div class="flex justify-end text-xs text-gray-600 opacity-50 absolute top-8 right-[3rem]">
            ${dayjs().format("YYYY-MM-DD")} @ 图灵智能创新团队
          </div>

          <!-- 个人信息头部 -->
          <div class="border-gray-800 relative flex items-end mb-16 mt-4 justify-between">
            <div class="flex-col flex gap-5 flex-1 flex-shrink-0">
              <div class="text-7xl text-black tracking-wider">
                ${resume.value.name || "姓名"}
              </div>
              <div class="text-4xl text-gray-600 tracking-wider">
                ${resume.value.direction || "发展方向"}
              </div>
            </div>

            <div class="text-lg font-light text-gray-500 tracking-wide flex-col flex absolute right-0 bottom-0">
              <div class="text-right">${resume.value.major || "专业"} | ${resume.value.class || "班级"}</div>
              <div class="text-right">${resume.value.phone || "联系方式"} | ${resume.value.email || "邮箱地址"}</div>
            </div>
          </div>

          <!-- 内容区域 -->
          <div class="flex flex-col gap-14">
            <!-- 兴趣爱好 -->
            <div class="group">
              <div
                class="text-2xl text-gray-900 uppercase tracking-wider pb-3 border-b-2 border-gray-200 group-hover:border-gray-400 duration-200 flex-col items-center"
              >
                <div class="flex items-center">
                  <div class="flex items-center">兴趣爱好</div>
                </div>
              </div>
              <div class="mt-2">
                <p class="text-gray-700 text-base leading-relaxed tracking-wide">
                  ${resume.value.hobbies || "请填写兴趣爱好"}
                </p>
              </div>
            </div>

            <!-- 个人规划 -->
            <div class="group">
              <div
                class="text-2xl text-gray-900 uppercase tracking-wider pb-3 border-b-2 border-gray-200 group-hover:border-gray-400 duration-200 flex-col items-center"
              >
                <div class="flex items-center">
                  <div class="flex items-center">个人规划</div>
                </div>
              </div>
              <div class="mt-2">
                <p class="text-gray-700 text-base leading-relaxed tracking-wide">
                  ${resume.value.personalPlan || "请填写个人规划"}
                </p>
              </div>
            </div>

            <!-- 对团队的期待 -->
            <div class="group">
              <div
                class="text-2xl text-gray-900 uppercase tracking-wider pb-3 border-b-2 border-gray-200 group-hover:border-gray-400 duration-200 flex-col items-center"
              >
                <div class="flex items-center">
                  <div class="flex items-center">对团队的期待</div>
                </div>
              </div>
              <div class="mt-2">
                <p class="text-gray-700 text-base leading-relaxed tracking-wide">
                  ${resume.value.joinReason || "请填写对团队的期待"}
                </p>
              </div>
            </div>

            <!-- 对本方向的理解，学习进度(如有) -->
            <div class="group">
              <div
                class="text-2xl text-gray-900 uppercase tracking-wider pb-3 border-b-2 border-gray-200 group-hover:border-gray-400 duration-200 flex-col items-center"
              >
                <div class="flex items-center">
                  <div class="flex items-center">对本方向的理解，学习进度(如有)</div>
                </div>
              </div>
              <div class="mt-2">
                <p class="text-gray-700 text-base leading-normal tracking-wide">
                  ${resume.value.skills || "请填写对本方向的理解，学习进度(如有)"}
                </p>
              </div>
            </div>
          </div>

          <!-- 底部标识 -->
          <div
            class="flex justify-between items-center text-gray-500 text-sm absolute bottom-8 w-full px-[3rem] right-0"
          >
            <div class="w-6 h-[1px] bg-gray-500"></div>
            <div>TURING</div>
            <div class="w-6 h-[1px] bg-gray-500"></div>
          </div>
        </div>
      `;

    // 添加临时容器到文档中
    document.body.appendChild(tempContainer);

    // 等待字体和样式加载完成
    await new Promise((resolve) => setTimeout(resolve, 100));

    // 使用html2canvas转换为canvas
    const canvas = await html2canvas(tempContainer.querySelector("#PDF-content") as HTMLElement, {
      scale: 2,
      useCORS: true,
      allowTaint: true,
      backgroundColor: "#ffffff",
      logging: false,
      width: 800,
      height: 1123,
      scrollX: 0,
      scrollY: 0
    });

    // 清理临时元素
    document.body.removeChild(tempContainer);

    const imgData = canvas.toDataURL("image/png", 1.0);
    const pdf = new jsPDF({
      orientation: "portrait",
      unit: "mm",
      format: "a4"
    });

    const pdfWidth = pdf.internal.pageSize.getWidth();
    const pdfHeight = (canvas.height * pdfWidth) / canvas.width;

    pdf.addImage(imgData, "PNG", 0, 2, pdfWidth, pdfHeight);

    const fileName = `${resume.value.name}"简历" ${dayjs().format("YYYY-MM-DD")}.pdf`;

    pdf.save(fileName);

    ElMessage.success("PDF简历下载成功！");
  } catch (e) {
    ElMessage.error("下载失败");
  }
};

const confirmSubmitAlert = async () => {
  return ElMessageBox.confirm("确定要提交并下载PDF简历吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    showClose: false,
    closeOnClickModal: false,
    closeOnPressEscape: false
  });
};

const downloadResumePDF = async (formEl: FormInstance | undefined) => {
  await confirmSubmitAlert();
  try {
    await formEl?.validate();

    const res = await postResumeMutation.mutateAsync(resume.value);

    if (res.status === 200) {
      resumeStore.setResumeData(resume.value);
      generatePDF();
    } else {
      ElMessage.error(res.message || "生成失败");
    }
  } catch (e) {
    ElMessage.error("请求失败");
  }
};
</script>

<style scoped></style>
